package com.gz.mylife.app;

import java.io.Serializable;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONObject;
import org.xutils.x;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;

import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.gz.mylife.Define;
import com.gz.mylife.R;
import com.gz.mylife.R.id;
import com.gz.mylife.util.NetworkUtil;
import com.gz.mylife.widget.FooterView;
import com.gz.mylife.widget.LoadingCover;
import com.gz.mylife.widget.OfflineDialog;
import com.gz.mylife.widget.FooterView.OnFooterViewRefreshListener;
import com.gz.mylife.widget.LoadingCover.OnLoadingCoverRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.zl.smartmall.library.ISmartMall;
import com.zl.smartmall.library.listener.GetMaintenaceListListener;
import com.zl.smartmall.library.listener.RequestCode;
import com.zl.smartmall.library.po.ForecastPrice;
import com.zl.smartmall.library.po.MaintenacesInfo;
import com.zl.smartmall.library.util.Constants;

public class MyEquipments extends BaseActivity implements OnItemClickListener,
OnRefreshListener<ListView>, OnFooterViewRefreshListener,
OnLoadingCoverRefreshListener {
	private static final String TAG = MyEquipments.class.getSimpleName();

	private PullToRefreshListView mPullList;

	private MyHandler mHandler;
	private List<MaintenacesInfo> mainList;
	private MyAdapter mAdapter;
	private LayoutInflater mInflater;
	private DisplayImageOptions options;

	private LoadingCover mLoadingCover;
	private OfflineDialog mOfflineDialog;
	private FooterView mFooterView;

	private int num;
	private String address;
	private String mallcomid;
	private List<ForecastPrice> forecast;//报价列表
	private MyAdapter1 myadapter1;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_my_equipmentlist);
		Bundle bundle = this.getIntent().getExtras();
		address = bundle.getString("address");
		mallcomid = bundle.getString("mallcomid");
		mainList = new ArrayList<MaintenacesInfo>();
		forecast = new ArrayList<ForecastPrice>();
		mHandler = new MyHandler(this);
		mInflater = getLayoutInflater();
		mAdapter = new MyAdapter();
		options = buildOptions();

		setActionbarTitle("维修列表", false);
		mPullList = (PullToRefreshListView) findViewById(R.id.list_equipment);
		mPullList.setAdapter(mAdapter);
		mPullList.setOnItemClickListener(this);
		mPullList.setOnRefreshListener(this);

		mFooterView = (FooterView) mInflater.inflate(R.layout.footer_view, null);
		mFooterView.setOnFooterViewRefreshListener(this);
		mPullList.getRefreshableView().addFooterView(mFooterView);
		mPullList.setOnScrollListener(mFooterView);

		mLoadingCover = (LoadingCover) findViewById(R.id.layout_loading_cover);
		mLoadingCover.setOnLoadingCoverRefreshListener(this);
		mOfflineDialog = (OfflineDialog) getLayoutInflater().inflate(R.layout.offline_dialog, null);
		//loadDataFromServer(buildListener(RequestCode.PULL));
	}

	private GetMaintenaceListListener buildListener(RequestCode requestCode) {
		return new GetMaintenaceListListener(requestCode) {
			@Override
			public void onResponseFailed() {
				// TODO Auto-generated method stub
				mLoadingCover.onRefreshFailed();
				//mFooterView.onRefreshFailed();
				if (mPullList.isRefreshing()) {
					mPullList.getLoadingLayoutProxy().refreshFailed();
				}
			}
			

			@Override
			public void onOffline() {
				// TODO Auto-generated method stub
				mOfflineDialog.show();
				mLoadingCover.onRefreshFailed(Define.MSG_OFFLINE_ERROR);
				if (mPullList.isRefreshing()) {
					mPullList.getLoadingLayoutProxy().refreshFailed();
				}
			}

			@Override
			public void onNoNetWork() {
				// TODO Auto-generated method stub
				if (mPullList.isRefreshing()) {
					mPullList.getLoadingLayoutProxy().refreshFailed();
				}
				mFooterView.onRefreshFailed();
				mLoadingCover.onRefreshFailed(Define.MSG_NO_NETWORK);
			}

			@Override
			public void onNoMoreData() {
				// TODO Auto-generated method stub
				if (mPullList.isRefreshing()) {
					mPullList.getLoadingLayoutProxy().refreshSuccess();
				}
				mFooterView.onRefreshComplete();
				mLoadingCover.onRefreshFailed(Define.MSG_NO_MORE_DATA);
			}

			@Override
			public void onResponseSuccess(List<MaintenacesInfo> mainInfos) {

				if (this.requestCode == RequestCode.PULL) {
					mainList.clear();
				}
				mainList.addAll(mainInfos);
				mAdapter.notifyDataSetChanged();
				if (mainInfos.size() < Define.LISTVIEW_ITEM_MIN_SIZE) {
					mFooterView.onRefreshComplete();
					mPullList.setOnScrollListener(null);
				} else {
					mAdapter.notifyDataSetChanged();
					mFooterView.onRefreshSuccess();//刷新成功并且后面还有数据可以进行加载
					mPullList.setOnScrollListener(mFooterView);
				}
				if (mPullList.isRefreshing()) {
					mPullList.getLoadingLayoutProxy().refreshSuccess();
				}
				mLoadingCover.onRefreshSuccess();
			}
		};
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mHandler.release();
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		if (view == mFooterView) {
			return;
		}

		Intent intent = new
				Intent(getApplicationContext(),MyEquimentDetail.class);
		intent.putExtra("mainlist", (Serializable)mainList.get(position-1));
		intent.putExtra("address", address);
		intent.putExtra("mallcomid", mallcomid);
		startActivityForResult(intent, Define.ACTIVITY_CODE_ORDER_DETAIL);

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch (resultCode) {
		case Define.ACTIVITY_CODE_ORDER_CANCEL:
		case Define.ACTIVITY_CODE_ORDER_PAID:
		case Define.ACTIVITY_CODE_ORDER_SIGN:
		case Define.ACTIVITY_CODE_APPLY_EXCHANGE:
			mPullList.setRefreshing();
			break;
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		loadDataFromServer(buildListener(RequestCode.PULL));
		// Tools.recordBehavious(getApplicationContext(), TAG
		// ,Define.BEHAVIOUS_RESUME);
	}

	@Override
	protected void onPause() {
		super.onPause();
		// Tools.recordBehavious(getApplicationContext(),
		// TAG,Define.BEHAVIOUS_PAUSE);
	}

	@Override
	public void onFooterViewRefresh() {
		// TODO Auto-generated method stub
		loadDataFromServer(buildListener(RequestCode.SCROLL));
	}

	@Override
	public void onLoadingCoverRefresh() {
		// TODO Auto-generated method stub
		loadDataFromServer(buildListener(RequestCode.PULL));
	}

	@Override
	public void onRefresh(PullToRefreshBase<ListView> refreshView) {
		// TODO Auto-generated method stub
		loadDataFromServer(buildListener(RequestCode.PULL));
	}

	private DisplayImageOptions buildOptions() {
		return new DisplayImageOptions.Builder().resetViewBeforeLoading(true)
				.bitmapConfig(Bitmap.Config.ARGB_8888).cacheInMemory(true)
				.cacheOnDisk(true)
				.showImageOnLoading(R.drawable.ic_load_image_square_default)
				.showImageOnFail(R.drawable.ic_load_image_square_fail)
				.imageScaleType(ImageScaleType.IN_SAMPLE_INT) // default
				.displayer(new RoundedBitmapDisplayer(5)).build();
	}

	private static class MyHandler extends Handler {

		private MyEquipments mOuter;

		public MyHandler(MyEquipments outer) {
			mOuter = outer;
		}

		public void handleMessage(android.os.Message msg) {
			if (mOuter == null) {
				return;
			}
			switch (msg.what) {
			case 1:// 刷新adapter
				mOuter.mAdapter.notifyDataSetChanged();
				break;

			default:
				break;
			}
		};

		public void release() {
			new WeakReference<MyEquipments>(mOuter);
		}
	};
	/**
	 * 适配器
	 * @author Administrator
	 *
	 */
	private class MyAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return mainList.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return mainList.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.myequiment_item, null);
				holder = new ViewHolder();
				holder.createtime = (TextView) convertView.findViewById(R.id.tv_create_time);
				holder.tvordernumber = (TextView) convertView.findViewById(R.id.tv_order_number);
				holder.status = (TextView) convertView.findViewById(R.id.tv_status);
				holder.username = (TextView) convertView.findViewById(R.id.username);
				holder.project = (TextView) convertView.findViewById(R.id.project);// 维修项目
				holder.address = (TextView) convertView.findViewById(R.id.address);// 维修地址
				holder.tv_forecastprice = (TextView) convertView.findViewById(R.id.tv_forecastprice);
				convertView.setTag(holder);

			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			final MaintenacesInfo info = mainList.get(position);
			holder.createtime.setText(info.getCreatedat());
			holder.tvordernumber.setText("维修单号：" + info.getCode());
			holder.username.setText(info.getApplyname());
			holder.project.setText(info.getRepairitem());
			holder.address.setText(info.getAddress());
			//显示维修申报的状态
			if ("待处理".equals(info.getStatus())) {
				holder.status.setText("待处理");
				holder.status.setTextColor(getResources().getColor(R.color.text_color_my_order_payed));
				holder.status.setBackgroundResource(R.drawable.bg_my_orders_frame_green);
			}
			else if("处理中".equals(info.getStatus())){
				holder.status.setText("处理中");
				holder.status.setTextColor(getResources().getColor(R.color.text_color_my_order_trade_successful));
				holder.status.setBackgroundResource(R.drawable.bg_my_orders_frame_orange);
			}
			else if("完成".equals(info.getStatus())||"已反馈".equals(info.getStatus())){
				holder.status.setText("完成");
				holder.status.setTextColor(getResources().getColor(R.color.text_color_my_order_no_pay));
				holder.status.setBackgroundResource(R.drawable.bg_my_orders_frame_red);
			}
			else if ("已派单".equals(info.getStatus())) {
				holder.status.setText("已派单");
				holder.status.setTextColor(getResources().getColor(R.color.text_color_my_order_trade_successful));
				holder.status.setBackgroundResource(R.drawable.bg_my_orders_frame_orange);
			}
			else if ("已接单".equals(info.getStatus())) {
				holder.status.setText("已接单");
				holder.status.setTextColor(getResources().getColor(R.color.text_color_my_order_trade_successful));
				holder.status.setBackgroundResource(R.drawable.bg_my_orders_frame_orange);
			}
			holder.tv_forecastprice.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					info_repair_list(info.getCom_id());
				}
			});
			return convertView;
		}
	}
	private class ViewHolder {
		TextView createtime;
		TextView tvordernumber;
		TextView status;
		TextView username;// 联系人
		TextView project;
		TextView address;// 维修地址
		TextView tv_forecastprice;//查看报价
	}
	private void loadDataFromServer(GetMaintenaceListListener getMaintenaceListListener) {	
		if(getMaintenaceListListener.getRequestCode() == RequestCode.PULL) {
			num = 1;
		}else if(getMaintenaceListListener.getRequestCode() == RequestCode.SCROLL) {
			num++;
		}
		ISmartMall.getInstance().getMaintenacesList(mallcomid,num,address, FragmentPersonal.mUserInfo.getUid()+"",getMaintenaceListListener);

	}
	/**
	 * 报价信息
	 */
	private void info_repair_list(int com_id) {

		if (NetworkUtil.isNetworkConnected(MyEquipments.this)) {
			String url = Constants.URL_HOST_RUBY+"/android_oa/info_repair_list";
			RequestParams params = new RequestParams(url);
			params.addParameter("com_id", com_id);
			Log.i("duzhijuan", params + "?com_id="+com_id);
			x.http().get(params, new Callback.CommonCallback<String>() {

				@Override
				public void onCancelled(CancelledException arg0) {
					// TODO Auto-generated method stub
					Log.e("cancelled", arg0.toString());
				}

				@Override
				public void onError(Throwable arg0, boolean arg1) {
					// TODO Auto-generated method stub
					Log.e("onError", arg0.toString());
				}

				@Override
				public void onFinished() {
					// TODO Auto-generated method stub
					Log.e("onFinished","onFinished");
				}

				@Override
				public void onSuccess(String result) {
					// TODO Auto-generated method stub
					try {
						JSONObject jsonObject = new JSONObject(result.toString());
						if ("0".equals(jsonObject.getString("ret"))) {
							forecast.clear();
							forecast.addAll(ForecastPrice.parse(jsonObject.getJSONArray("result")));
							if (forecast.size()>0) {
								createDialog();
							}else{
								Toast.makeText(MyEquipments.this, jsonObject.getString("~暂时没有报价~"), Toast.LENGTH_LONG).show();
							}
						}else{
							Toast.makeText(MyEquipments.this, jsonObject.getString("msg"), Toast.LENGTH_LONG).show();
						}
					} catch (Exception e) {
						// TODO: handle exception
					}
				}

			});
		}else{
			Toast.makeText(MyEquipments.this, "糟糕,网络异常!", Toast.LENGTH_LONG).show();
		}

	}

	private void createDialog() {
		final AlertDialog dialog = new AlertDialog.Builder(this).create();
		View view = LayoutInflater.from(this).inflate(R.layout.forecastprice_dialog, null);
		dialog.setView(view, 0, 0, 0, 0);
		dialog.show();
		dialog.setCanceledOnTouchOutside(true);//弹出框周围点击不起作用，返回键还起作用
		DisplayMetrics metrics=new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		int widthPixels=metrics.widthPixels;
		WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
		params.width = widthPixels-40;
		dialog.getWindow().setAttributes(params);
		ListView forecast = (ListView) view.findViewById(R.id.tv_title);
		myadapter1 = new MyAdapter1();
		forecast.setAdapter(myadapter1);
		Button btn_change = (Button) view.findViewById(R.id.btn_change);
		btn_change.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		});

	}
	
	private class MyAdapter1 extends BaseAdapter {

		@Override
		public int getCount() {
			return forecast.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return forecast.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder1 holder;
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.forecast_item, null);
				holder = new ViewHolder1();
				holder.forecast_name = (TextView) convertView.findViewById(R.id.forecast_name);
				holder.forecast_price = (TextView) convertView.findViewById(R.id.forecast_price);
				holder.forecast_unit = (TextView) convertView.findViewById(R.id.forecast_unit);
				convertView.setTag(holder);

			} else {
				holder = (ViewHolder1) convertView.getTag();
			}
			holder.forecast_name.setText(forecast.get(position).getName());
			holder.forecast_price.setText(forecast.get(position).getPrice());
			holder.forecast_unit.setText(forecast.get(position).getUnit());
			return convertView;
		}
	}
	private class ViewHolder1 {
		TextView forecast_name;
		TextView forecast_price;
		TextView forecast_unit;
		
	}
}
